package com.csnf.servlet;

import com.csnf.dao.ICourseDao;
import com.csnf.dao.impl.ICourseDaoImpl;
import com.csnf.entity.course;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;

@WebServlet({"/getAllCourse","/getCourseByName","/deleteCourse","/addCourse"})
public class CourseServlet extends HttpServlet {
    private ICourseDao courseDao = new ICourseDaoImpl();

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        List<course> courseList = null;
        switch (servletPath){
            case "/getAllCourse":
                courseList = courseDao.getAllCourse();
                request.setAttribute("courseList", courseList);
                request.getRequestDispatcher("/courseList.jsp").forward(request, response);
                break;
            case "/getCourseByName":
                String name = request.getParameter("name");
                if (name != null){
                    request.setAttribute("courseList", courseDao.getCourseByName(name));
                }else {
                    request.setAttribute("courseList", courseDao.getAllCourse());
                }
                request.getRequestDispatcher("/courseList.jsp").forward(request, response);
                break;
            case "/deleteCourse":
                courseDao.deleteCourse(Integer.parseInt(request.getParameter("id")));
                request.getRequestDispatcher("/getAllCourse").forward(request, response);
                break;
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String servletPath = request.getServletPath();
        String name = request.getParameter("name");
        Integer count = Integer.parseInt(request.getParameter("count"));
        LocalDate startDate = LocalDate.parse(request.getParameter("startDate"));
        LocalDate endDate = LocalDate.parse(request.getParameter("endDate"));
        String teacher = request.getParameter("teacher");
        switch (servletPath){
            case "/addCourse":
                courseDao.addCourse(new course(null,name, count, startDate, endDate, teacher));
                break;
        }
        request.setAttribute("courseList", courseDao.getAllCourse());
        request.getRequestDispatcher("courseList.jsp").forward(request, response);
    }
}
